package com.ccjq.shosestore.core.utils;


import org.apache.commons.lang3.StringUtils;

import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;

/**
 *  describe:UUID生成工具类
 *
 */
public class UuidUtils {
    /**
     * 获取唯一标识
     *
     * @return 返回长度为19位纯数字唯一标识

     */
    public static long generateShortUUID(){
        long t1 = 0x7FFFFFFF & System.currentTimeMillis();
        Random random = new Random();
        return t1 << 32 | Math.abs(random.nextInt());
    }

    /**
     * 获取唯一标识
     *
     * @param prefix 前缀
     * @param length 长度(不包括前缀，最大长度19位;长度越短重复的几率越高)
     * @return 返回指定前缀和长度的唯一标识
     */
    public static String generateShortUUID(String prefix , int length){
        String uuid = UUID.randomUUID().toString().replace("-","");
        String shortUUID = String.valueOf(generateShortUUID());
        char[] uuidChars = uuid.toCharArray();
        char[] shortuuidChars = shortUUID.toCharArray();
        StringBuilder builder = new StringBuilder(StringUtils.isBlank(prefix) ? "" :prefix);
        if(length < 0){
            length = shortUUID.length();
        }
        for(int i = 0; i < length ; i++){
            int index = Integer.parseInt(String.valueOf(shortuuidChars[i]));
            builder.append(String.valueOf(uuidChars[index]));
        }
        return builder.toString().toUpperCase();
    }
    /**
     * 测试
     *
     * @param args
     */
    public static void main(String[] args)
    {
        Set<String> stuNoSet = new TreeSet<String>();
        int count = 60000;
        for(int i = 0 ; i < count ; i++){
            String studentNo = generateShortUUID("SP",9);
            stuNoSet.add(studentNo);
            System.out.println("studentNo = "+studentNo);
        }
        if(stuNoSet.size() == count){
            System.out.println("测试生成" + count + "个学号，无重复！");
        }else{
            System.out.println("测试生成" + count + "个学号，重复个数：" +(count - stuNoSet.size()));
        }

        System.out.println("--------------------------------------------------------");
    }
}
